package com.skp.shaphan.io;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

public class JSONDataWriter extends StringBasedDataWriter {
	private JSONObject data;
	private ArrayList<String> keys;
	private boolean firstRow;

	@Override
	protected void createStreams(OutputStream stream) throws IOException {
		super.createStreams(stream);
		println("[");
	}

	@Override
	public void close() throws IOException {
		println("]");
		super.close();
	}

	@Override
	public void closeRow() {
		super.closeRow();
		if(firstRow) {
			firstRow = false;
		} else {
			print(",");
		}
		println(data.toString());
	}

	@Override
	public void setMetaData(ResultSetMetaData meta) throws SQLException {
		super.setMetaData(meta);
		data = new JSONObject();
		keys = new ArrayList<String>();
		firstRow = true;
		for(int x=1; x<=meta.getColumnCount(); x++) {
			try {
				data.putOnce(meta.getColumnName(x), null);
				keys.add(meta.getColumnName(x));
			} catch (JSONException e) {
				throw new SQLException("Could not add column: " + meta.getColumnName(x) + " -- " + e.getLocalizedMessage(), e);
			}
		}
	}

	@Override
	protected void writeNewRowData() {
		super.writeNewRowData();
	}

	@Override
	protected void writeCellData(String data, int columnNumber) {
		super.writeCellData(data, columnNumber);
		try {
			this.data.put(keys.get(columnNumber - 1), data);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
